<template>
  <div class="maintenance-list">
    <!-- 搜索区域 -->
    <Card title="搜索条件" :bordered="false" style="margin-bottom: 16px">
      <Row :gutter="16">
        <Col :span="6">
          <Form.Item label="关键词">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="请输入记录名称或资源名称"
              allow-clear
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="维护类型">
            <Select
              v-model:value="searchForm.maintenanceType"
              placeholder="请选择维护类型"
              allow-clear
              :options="maintenanceTypeOptions"
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              :options="statusOptions"
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="资源类型">
            <Select
              v-model:value="searchForm.resourceType"
              placeholder="请选择资源类型"
              allow-clear
              :options="resourceTypeOptions"
            />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col :span="24" style="text-align: right">
          <Space>
            <Button @click="resetSearch">重置</Button>
            <Button type="primary" @click="handleSearch">搜索</Button>
          </Space>
        </Col>
      </Row>
    </Card>

    <!-- 数据表格 -->
    <Card :bordered="false">
      <Table
        :columns="columns"
        :data-source="recordList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'maintenanceType'">
            <Tag :color="getMaintenanceTypeColor(record.maintenanceType)">
              {{ getMaintenanceTypeLabel(record.maintenanceType) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'actualCost'">
            <span v-if="record.actualCost"
              >¥{{ record.actualCost.toLocaleString() }}</span
            >
            <span v-else>-</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                详情
              </Button>
              <Select
                v-if="record.status === 'PENDING'"
                size="small"
                style="width: 100px"
                placeholder="更新状态"
                @change="(value) => updateStatus(record.id, value)"
              >
                <SelectOption value="IN_PROGRESS">开始执行</SelectOption>
                <SelectOption value="CANCELLED">取消</SelectOption>
              </Select>
              <Select
                v-else-if="record.status === 'IN_PROGRESS'"
                size="small"
                style="width: 100px"
                placeholder="更新状态"
                @change="(value) => updateStatus(record.id, value)"
              >
                <SelectOption value="COMPLETED">完成</SelectOption>
                <SelectOption value="CANCELLED">取消</SelectOption>
              </Select>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 维护记录详情 -->
    <Modal
      v-model:open="detailVisible"
      title="维护记录详情"
      width="800px"
      :footer="null"
    >
      <div v-if="currentRecord" class="record-detail">
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-item">
              <label>维护名称：</label>
              <span>{{ currentRecord.name }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-item">
              <label>资源名称：</label>
              <span>{{ currentRecord.resourceName }}</span>
            </div>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-item">
              <label>维护类型：</label>
              <Tag
                :color="getMaintenanceTypeColor(currentRecord.maintenanceType)"
              >
                {{ getMaintenanceTypeLabel(currentRecord.maintenanceType) }}
              </Tag>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-item">
              <label>状态：</label>
              <Tag :color="getStatusColor(currentRecord.status)">
                {{ getStatusLabel(currentRecord.status) }}
              </Tag>
            </div>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-item">
              <label>计划日期：</label>
              <span>{{ currentRecord.plannedDate }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-item">
              <label>执行日期：</label>
              <span>{{ currentRecord.executionDate || '-' }}</span>
            </div>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-item">
              <label>预计时长：</label>
              <span>{{ currentRecord.estimatedDuration }}小时</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-item">
              <label>实际时长：</label>
              <span>{{ currentRecord.actualDuration || '-' }}小时</span>
            </div>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-item">
              <label>预计成本：</label>
              <span>¥{{ currentRecord.estimatedCost.toLocaleString() }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-item">
              <label>实际成本：</label>
              <span>{{
                currentRecord.actualCost
                  ? `¥${currentRecord.actualCost.toLocaleString()}`
                  : '-'
              }}</span>
            </div>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-item">
              <label>负责人：</label>
              <span>{{ currentRecord.assignee }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-item">
              <label>执行人：</label>
              <span>{{ currentRecord.executor || '-' }}</span>
            </div>
          </Col>
        </Row>
        <div class="detail-section">
          <h4>维护描述</h4>
          <p>{{ currentRecord.description }}</p>
        </div>
        <div class="detail-section">
          <h4>备注</h4>
          <p>{{ currentRecord.notes || '无' }}</p>
        </div>
        <div v-if="currentRecord.findings" class="detail-section">
          <h4>维护发现</h4>
          <p>{{ currentRecord.findings }}</p>
        </div>
        <div v-if="currentRecord.nextMaintenance" class="detail-section">
          <h4>下次维护</h4>
          <p>{{ currentRecord.nextMaintenance }}</p>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const recordList = ref<any[]>([]);
const detailVisible = ref(false);
const currentRecord = ref<any>(null);

const searchForm = reactive({
  keyword: '',
  maintenanceType: '',
  status: '',
  resourceType: '',
  dateRange: [],
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 维护类型选项
const maintenanceTypeOptions = [
  { label: '预防性维护', value: 'PREVENTIVE' },
  { label: '定期维护', value: 'PERIODIC' },
  { label: '紧急维修', value: 'EMERGENCY' },
  { label: '设备升级', value: 'UPGRADE' },
];

// 状态选项
const statusOptions = [
  { label: '待执行', value: 'PENDING' },
  { label: '执行中', value: 'IN_PROGRESS' },
  { label: '已完成', value: 'COMPLETED' },
  { label: '已取消', value: 'CANCELLED' },
];

// 资源类型选项
const resourceTypeOptions = [
  { label: '设备', value: 'EQUIPMENT' },
  { label: '设施', value: 'FACILITY' },
  { label: '车辆', value: 'VEHICLE' },
  { label: '系统', value: 'SYSTEM' },
];

// 表格列定义
const columns = [
  {
    title: '维护记录',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
    width: 150,
  },
  {
    title: '维护类型',
    dataIndex: 'maintenanceType',
    key: 'maintenanceType',
    width: 120,
  },
  {
    title: '执行日期',
    dataIndex: 'executionDate',
    key: 'executionDate',
    width: 120,
  },
  {
    title: '实际时长',
    dataIndex: 'actualDuration',
    key: 'actualDuration',
    width: 100,
  },
  {
    title: '实际成本',
    dataIndex: 'actualCost',
    key: 'actualCost',
    width: 120,
  },
  {
    title: '执行人',
    dataIndex: 'executor',
    key: 'executor',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const,
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: '1',
        name: '空调系统年度维护',
        resourceId: 'AC001',
        resourceName: '中央空调系统',
        maintenanceType: 'PREVENTIVE',
        description: '年度预防性维护，包括清洁、检查、更换滤网等',
        plannedDate: '2024-03-15',
        executionDate: '2024-03-15',
        estimatedDuration: 4,
        actualDuration: 3.5,
        estimatedCost: 2000,
        actualCost: 1800,
        priority: 'MEDIUM',
        status: 'COMPLETED',
        assignee: '张师傅',
        executor: '张师傅',
        notes: '需要提前准备滤网和清洁剂',
        findings: '滤网需要更换，系统运行正常',
        nextMaintenance: '2025-03-15',
      },
      {
        id: '2',
        name: '电梯紧急维修',
        resourceId: 'EL001',
        resourceName: '客梯1号',
        maintenanceType: 'EMERGENCY',
        description: '电梯运行异常，需要紧急检查和维修',
        plannedDate: '2024-03-10',
        executionDate: '2024-03-10',
        estimatedDuration: 2,
        actualDuration: 2.5,
        estimatedCost: 1500,
        actualCost: 1800,
        priority: 'URGENT',
        status: 'COMPLETED',
        assignee: '李师傅',
        executor: '李师傅',
        notes: '已联系电梯公司技术人员',
        findings: '传感器故障，已更换',
        nextMaintenance: '2024-06-10',
      },
      {
        id: '3',
        name: '锅炉设备升级',
        resourceId: 'BL001',
        resourceName: '锅炉系统',
        maintenanceType: 'UPGRADE',
        description: '升级锅炉控制系统，提高能效',
        plannedDate: '2024-03-20',
        executionDate: null,
        estimatedDuration: 8,
        actualDuration: null,
        estimatedCost: 15000,
        actualCost: null,
        priority: 'HIGH',
        status: 'PENDING',
        assignee: '王师傅',
        executor: null,
        notes: '需要停用锅炉24小时',
        findings: null,
        nextMaintenance: null,
      },
    ];

    recordList.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error('加载维护记录失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    maintenanceType: '',
    status: '',
    resourceType: '',
    dateRange: [],
  });
  handleSearch();
};

// 查看详情
const viewDetail = (record: any) => {
  currentRecord.value = record;
  detailVisible.value = true;
};

// 更新状态
const updateStatus = (id: string, status: string) => {
  const record = recordList.value.find((item) => item.id === id);
  if (record) {
    record.status = status;
    if (status === 'IN_PROGRESS') {
      record.executionDate = new Date().toISOString().split('T')[0];
    } else if (status === 'COMPLETED') {
      record.actualDuration = record.estimatedDuration;
      record.actualCost = record.estimatedCost;
      record.executor = record.assignee;
    }
    message.success('状态更新成功');
  }
};

// 辅助函数
const getMaintenanceTypeColor = (type: string) => {
  const colors = {
    PREVENTIVE: 'blue',
    PERIODIC: 'green',
    EMERGENCY: 'red',
    UPGRADE: 'purple',
  };
  return colors[type] || 'default';
};

const getMaintenanceTypeLabel = (type: string) => {
  const labels = {
    PREVENTIVE: '预防性维护',
    PERIODIC: '定期维护',
    EMERGENCY: '紧急维修',
    UPGRADE: '设备升级',
  };
  return labels[type] || type;
};

const getStatusColor = (status: string) => {
  const colors = {
    PENDING: 'orange',
    IN_PROGRESS: 'blue',
    COMPLETED: 'green',
    CANCELLED: 'red',
  };
  return colors[status] || 'default';
};

const getStatusLabel = (status: string) => {
  const labels = {
    PENDING: '待执行',
    IN_PROGRESS: '执行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
  };
  return labels[status] || status;
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.maintenance-list {
  padding: 20px;
}

.record-detail {
  padding: 16px;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: bold;
  margin-right: 8px;
  min-width: 80px;
}

.detail-section {
  margin-top: 24px;
}

.detail-section h4 {
  margin-bottom: 8px;
  color: #1890ff;
}

.detail-section p {
  margin: 0;
  line-height: 1.6;
  color: #666;
}
</style>
